package com.schezhi.link.executor.dynamic;

import com.alibaba.druid.pool.DruidDataSource;
import com.cqfan.cloud.framework.utils.BeanUtils;
import com.schezhi.link.model.datasource.LinkDataSourceVO;
import lombok.Getter;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author JiaLing.Fan
 * @version 1.0
 * @date 2023/10/18 11:42
 * @description DynamicDataSourceConfig
 */

@Configuration
public class DynamicDataSourceConfig {


    @Getter
    public Map<Long, LinkDataSourceVO> dataSourceMap = new ConcurrentHashMap<>();


    @Bean
    public DynamicDataSource dynamicDataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map<Object, Object> targetDataSources =  getDynamicDataSource();
        if(targetDataSources.size() < 2){
            throw new RuntimeException("没有可用数据源");
        }

        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(targetDataSources.get(0));
        return dynamicDataSource;
    }


    public static String getLocalIP() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }

    @SneakyThrows
    private Map<Object, Object> getDynamicDataSource(){
        List<LinkDataSourceVO>  syncDataSourceVOList = new ArrayList<>();
        DataSourceProperty dataSourceProperty = new DataSourceProperty();
        Map<Object, Object> targetDataSources = new ConcurrentHashMap<>(syncDataSourceVOList.size());
        LinkDataSourceVO linkDataSourceVO = new LinkDataSourceVO();
        DruidDataSource druidDataSource = DynamicDataSourceFactory.buildDruidDataSource(dataSourceProperty);
        dataSourceMap.put(1L , linkDataSourceVO);


        syncDataSourceVOList.forEach((e) ->{


        });
        return targetDataSources;
    }

}
